package com.szh.mysobproject.ui.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.core.content.getSystemService
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import by.kirich1409.viewbindingdelegate.viewBinding
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.hjq.bar.TitleBar
import com.hjq.umeng.Platform
import com.hjq.umeng.UmengShare
import com.szh.mysobproject.R
import com.szh.mysobproject.action.OnBack2TopListener
import com.szh.mysobproject.action.StatusAction
import com.szh.mysobproject.app.AppActivity
import com.szh.mysobproject.app.TitleBarFragment
import com.szh.mysobproject.databinding.FishListFragmentBinding
import com.szh.mysobproject.manager.UserManager
import com.szh.mysobproject.model.Fish
import com.szh.mysobproject.ui.activity.FishPondDetailActivity
import com.szh.mysobproject.ui.activity.ImagePreviewActivity
import com.szh.mysobproject.ui.activity.LoginActivity
import com.szh.mysobproject.ui.activity.PutFishActivity
import com.szh.mysobproject.ui.adapter.AdapterDelegate
import com.szh.mysobproject.ui.adapter.EmptyAdapter
import com.szh.mysobproject.ui.adapter.FishListAdapter
import com.szh.mysobproject.ui.dialog.MessageDialog
import com.szh.mysobproject.ui.dialog.ShareDialog
import com.szh.mysobproject.util.*
import com.szh.mysobproject.viewmodel.app.AppViewModel
import com.szh.mysobproject.viewmodel.fishpond.FishPondViewModel
import com.szh.mysobproject.widget.StatusLayout
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject


/**
 * @author : create by  szh
 * @date : 2022/6/24 9:08
 * @desc :摸鱼动态列表 Fragment
 */

@AndroidEntryPoint
class FishListFragment : TitleBarFragment<AppActivity>(), StatusAction, OnBack2TopListener {

    private val mBinding: FishListFragmentBinding by viewBinding()
    private var isShowing = false
    private var clickLogin = false

    @Inject
    lateinit var mAppViewModel: AppViewModel
    private val mFishPondViewModel by activityViewModels<FishPondViewModel>()
    private val mFishListAdapter = FishListAdapter(AdapterDelegate())
    private val loadStateListener = loadStateListener(mFishListAdapter) {
        mBinding.refreshLayout.finishRefresh()
    }


    override fun getLayoutId(): Int = R.layout.fish_list_fragment

    override fun initObserver() {}

    override fun initEvent() {
        val ivPublishContent = mBinding.ivPublishContent
        mBinding.titleBar.setDoubleClickListener {
            onBack2Top()
        }
        mBinding.refreshLayout.setOnRefreshListener {
            mFishListAdapter.refresh()
        }
        // 需要在 View 销毁的时候移除 listener
        mFishListAdapter.addLoadStateListener(loadStateListener)
        mFishListAdapter.setOnItemClickListener { item, _ ->
            val momentId = item.id
            FishPondDetailActivity.start(requireContext(), momentId)
        }
        mFishListAdapter.setOnMenuItemClickListener { view, item, position ->
            when (view.id) {
                R.id.ll_share -> shareFish(item)                //分享
                R.id.ll_great -> dynamicLikes(item, position)   //点赞
            }
        }

        ivPublishContent.setFixOnClickListener {
            takeIfLogin {
                startActivityForResult(PutFishActivity::class.java) { resultCode, _ ->
                    if (resultCode == Activity.RESULT_OK) {
                        mFishListAdapter.refresh()
                    }
                }
            }
            //TODO:使用第三方框架
//            PictureSelector.create(this)
//                .openGallery(SelectMimeType.ofImage())
//                .setImageEngine(GlideEngine.createGlideEngine())
//                .forResult(object : OnResultCallbackListener<LocalMedia> {
//                    override fun onResult(result: ArrayList<LocalMedia>?) {
//
//                    }
//
//                    override fun onCancel() {
//
//                    }
//                })

        }

        mFishListAdapter.setOnNineGridClickListener { sources, index ->
            ImagePreviewActivity.start(requireContext(), sources, index)
        }
        mBinding.rvFishPondList.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            /**
             * 当前是否显示
             */
            private var mIsShowing = true

            /**
             * 当前是否向上滑动
             */
            private var mIsUp = false

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                when (newState) {
                    // RecyclerView 当前未滚动
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 如果手指是向下滑动且当前没有显示 --> 显示悬浮按钮
                        if (mIsUp.not() && mIsShowing.not()) {
                            ivPublishContent.show()
                            mIsShowing = true
                        }
                    }
                    // 1、RecyclerView 当前正被外部输入（例如用户触摸输入）拖动
                    // 2、RecyclerView 当前正在动画到最终位置，而不受外部控制
                    RecyclerView.SCROLL_STATE_DRAGGING, RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 如果当前已经显示了悬浮按钮 --> 隐藏
                        if (mIsShowing) {
                            ivPublishContent.hide()
                        }
                        mIsShowing = false
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                // Timber.d("onScrolled：===> dy is $dy")
                mIsUp = dy > 0
            }
        })
    }

    private fun dynamicLikes(item: Fish.FishItem, position: Int) {
        val currUserId = UserManager.loadCurrUserId()
        //检查是否登录
        if (currUserId.isNotEmpty()) {
            val thumbUpList = item.thumbUpList
            if (thumbUpList.contains(currUserId)) {
                toast("请不要重复点赞")
            } else {
                thumbUpList.add(currUserId)
                mFishListAdapter.notifyItemChanged(position)
            }
            tryVibrate()
            mFishPondViewModel.dynamicLikes(item.id).observe(this) {}
        } else {

            if (isShowing) {
                return
            }
            MessageDialog.Builder(requireContext())
                .setTitle("系统消息")
                .setMessage("账号未登录，是否登录？")
                .setConfirm("现在登录")
                .setCancel("暂不登录")
                .addOnShowListener {
                    isShowing = true
                    clickLogin = true
                }
                .addOnDismissListener {
                    isShowing = false
                }
                .setListener {
                    LoginActivity.start(requireContext(), "", "")
                }.show()
        }
    }

    @SuppressLint("MissingPermission")
    private fun tryVibrate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            requireContext().getSystemService<Vibrator>()?.let { vibrator ->
                if (vibrator.hasVibrator()) {
                    val ve = VibrationEffect.createOneShot(
                        80,
                        VibrationEffect.DEFAULT_AMPLITUDE
                    )
                    vibrator.vibrate(ve)
                }
            }
        }
    }

    private fun shareFish(item: Fish.FishItem) {
        val momentId = item.id
        val content = UMWeb(SUNNY_BEACH_FISH_URL_PRE + momentId)
        content.title = "我发布了一条摸鱼动态，快来看看吧~"
        content.setThumb(UMImage(requireContext(), R.mipmap.launcher_ic))
        content.description = getString(R.string.app_name)
        //分享
        ShareDialog.Builder(requireActivity())
            .setShareLink(content)
            .setListener(object : UmengShare.OnShareListener {

                override fun onSucceed(platform: Platform?) {
                    toast("分享成功")
                }

                override fun onError(platform: Platform?, t: Throwable) {
                    toast(t.message)
                }

                override fun onCancel(platform: Platform?) {
                    toast("取消分享")
                }

            })
            .show()
    }

    override fun initData() {
        loadFishList()
        mAppViewModel.getMourningCalendar().observe(viewLifecycleOwner) {
            val result = it.getOrNull() ?: return@observe
            val sdf = SimpleDateFormat("MM月dd日", Locale.getDefault())
            val formatDate = sdf.format(System.currentTimeMillis())
            val rootView = requireView()
            result.forEach { mourningCalendar ->
                val date = mourningCalendar.date
                if (date == formatDate) {
                    rootView.setMourningStyle()
                }
            }
        }
    }

    private fun loadFishList() {
        viewLifecycleOwner.lifecycleScope.launchWhenCreated {
            mFishPondViewModel.getFishListByCategoryId("recommend").collectLatest {
                onBack2Top()
                mFishListAdapter.submitData(it)
            }
        }
    }

    override fun initView() {
        val emptyAdapter = EmptyAdapter()
        val concatAdapter = ConcatAdapter(emptyAdapter, mFishListAdapter)
        mBinding.rvFishPondList.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = concatAdapter
            addItemDecoration(SimpleLinearSpaceItemDecoration(6.dp))
        }
    }

    override fun onRightClick(titleBar: TitleBar?) {
        //TODO:跳转到扫码页面
    }

    override fun getStatusLayout(): StatusLayout = mBinding.hlFishPondHint

    override fun isStatusBarEnabled(): Boolean {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mFishListAdapter.removeLoadStateListener(loadStateListener)
    }

    override fun onBack2Top() {
        mBinding.rvFishPondList.scrollToPosition(0)
    }

    companion object {

        private val REQUEST_CODE_SCAN_ONE = hashCode()

        @JvmStatic
        fun newInstance() = FishListFragment()
    }
}